package com.lcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcp.entity.DietRecord;
import com.lcp.mapper.DietRecordMapper;
import com.lcp.service.DietRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DietRecordServiceImpl implements DietRecordService {

    @Autowired
    private DietRecordMapper dietRecordMapper;

    @Override
    public DietRecord getById(Long id) {
        return dietRecordMapper.selectById(id);
    }

    @Override
    public List<DietRecord> listByUserId(Long userId) {
        return dietRecordMapper.selectList(
            new QueryWrapper<DietRecord>()
                .eq("user_id", userId)
                .orderByDesc("meal_time")
        );
    }

    @Override
    public DietRecord create(DietRecord record) {
        record.setCreateTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        dietRecordMapper.insert(record);
        return record;
    }

    @Override
    public DietRecord update(DietRecord record) {
        record.setUpdateTime(LocalDateTime.now());
        dietRecordMapper.updateById(record);
        return record;
    }

    @Override
    public void delete(Long id) {
        dietRecordMapper.deleteById(id);
    }

    @Override
    public List<DietRecord> listByDateRange(Long userId, String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = LocalDateTime.parse(startDate + " 00:00:00", formatter);
        LocalDateTime end = LocalDateTime.parse(endDate + " 23:59:59", formatter);
        
        return dietRecordMapper.selectList(
            new QueryWrapper<DietRecord>()
                .eq("user_id", userId)
                .between("meal_time", start, end)
                .orderByDesc("meal_time")
        );
    }

    @Override
    public List<DietRecord> listByMealType(Long userId, String mealType, String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = LocalDateTime.parse(date + " 00:00:00", formatter);
        LocalDateTime end = LocalDateTime.parse(date + " 23:59:59", formatter);
        
        return dietRecordMapper.selectList(
            new QueryWrapper<DietRecord>()
                .eq("user_id", userId)
                .eq("meal_type", mealType)
                .between("meal_time", start, end)
                .orderByAsc("meal_time")
        );
    }

    @Override
    public Map<String, Object> getDailyNutritionSummary(Long userId, String date) {
        List<DietRecord> records = listByDateRange(userId, date, date);
        
        Map<String, Object> summary = new HashMap<>();
        summary.put("totalCalories", records.stream()
            .mapToInt(DietRecord::getCalories)
            .sum());
            
        summary.put("mealCount", records.size());
        
        summary.put("mealTypes", records.stream()
            .collect(Collectors.groupingBy(
                DietRecord::getMealType,
                Collectors.counting()
            )));
            
        summary.put("foodTypes", records.stream()
            .collect(Collectors.groupingBy(
                DietRecord::getFoodType,
                Collectors.counting()
            )));
            
        return summary;
    }

    @Override
    public Map<String, Object> getWeeklyNutritionTrend(Long userId, String startDate, String endDate) {
        List<DietRecord> records = listByDateRange(userId, startDate, endDate);
        
        Map<String, Object> trend = new HashMap<>();
        trend.put("dailyCalories", records.stream()
            .collect(Collectors.groupingBy(
                record -> record.getMealTime().toLocalDate().toString(),
                Collectors.summingInt(DietRecord::getCalories)
            )));
            
        trend.put("mealTypeDistribution", records.stream()
            .collect(Collectors.groupingBy(
                DietRecord::getMealType,
                Collectors.counting()
            )));
            
        trend.put("foodTypeDistribution", records.stream()
            .collect(Collectors.groupingBy(
                DietRecord::getFoodType,
                Collectors.counting()
            )));
            
        return trend;
    }
} 